package com.isoft.service.impl;


import com.isoft.exception.PasswordErrorException;
import com.isoft.mapper.UserMapper;
import com.isoft.pojo.dto.UserLoginDTO;
import com.isoft.pojo.entity.SystemUserLogin;
import com.isoft.properties.JwtProperties;
import com.isoft.service.UserService;
import com.isoft.utils.JwtUtil;
import com.isoft.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.isoft.exception.AccountNotFoundException;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImlp implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public SystemUserLogin login(UserLoginDTO userLoginDTO) {
        // 从数据库中获取用户信息
        SystemUserLogin user = userMapper.login(userLoginDTO);
        //判断账号是否存在
        if (user == null) {
            AccountNotFoundException exception = new AccountNotFoundException("账号不存在");
            throw exception;
        }
        // 对前端输入的密码进行MD5加密
        String encryptedPassword = PasswordUtil.encryptToMD5(userLoginDTO.getPassword());
        // 比对加密后的密码与数据库中的密码
        if (!PasswordUtil.comparePassword(encryptedPassword, user.getPassword())) {
            //密码不一致抛出异常
            PasswordErrorException exception = new PasswordErrorException("密码错误");
            throw exception;
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("username", user.getUsername());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        return new SystemUserLogin(user.getId(), user.getUsername(), null, token, user.getRealName()); // 不返回密码
    }


}
